<?php
namespace app\index\controller;
use app\model\Msg as MsgModel;
use think\Db;

use app\lib\baidu\Api as baiduApi;
use app\lib\baidu\Api360 as api360;
use app\lib\baidu\Tongyi as TongyiApi;

require_once '../extend/baidu.bos/BaiduBce.phar';
use BaiduBce\BceClientConfigOptions;
use BaiduBce\Util\MimeTypes;
use BaiduBce\Http\HttpHeaders;
use BaiduBce\Services\Bos\BosClient;


class Msg extends Base
{
    public function __construct(){
        $model = new MsgModel();
        $this->model = $model;
        parent::__construct();
        
        $page_info = $this->page_info;
        $page_info['title'] = '分类';

        $this->assign([
            'model'=>$this->model,
            'page_info'=>$page_info
        ]);
    }

    public function assignFields(){
        $model = $this->model;
        $companys = Db::name('company')->select();
        $companys = arrayParamExtract($companys,'id','name');

        $fields = [
            'company_id'=>['name'=>'所属公司','type'=>'select2_1','params'=>$companys],
            'name'=>['name'=>'部门名称','type'=>'text','valids'=>['required']],
            'code'=>['name'=>'部门代码','type'=>'text'],
        ];
        $valids = createPageValid($fields);
        $this->assign([
            'fields'=>$fields,
            'valids'=>$valids
        ]);

    }

    public function assignSearchs(){
        $model = $this->model;
        $companys = Db::name('company')->select();
        $companys = arrayParamExtract($companys,'id','name');

        $search_params = [
            [
                ['key'=>'company_id','name'=>'所属公司','type'=>'select1_1','params'=>$companys],
                ['key'=>'name','name'=>'部门名称','type'=>'text'],
                ['key'=>'code','name'=>'部门代码','type'=>'text'],
            ]
        ];
        $this->assign([
            'search_params'=>$search_params
        ]);
    }

    public function index($session_sn){
        $ulogin = $this->login_user;
        $model = $this->model;
        // $map_params = [
        //     ['key'=>'session_sn','type'=>'='],
        // ];
        // $map = getSearchParam($map_params);
        $map = [
            ['session_sn','=',$session_sn],
            ['user_id','=',$ulogin['id']]
        ];

        $list = $model->where($map)->order('id','asc')->select();
        $msg = [];
        foreach ($list as $k => $vo) {
            $ctime = date('Y-m-d',$vo['ctime']);
            // $vo['ctime'] = date('h:i a',$vo['ctime']);
            // $vo['rtime'] = date('h:i a',$vo['ctime']);
            $vo['ctime'] = date('H:i:s',$vo['ctime']);
            $vo['rtime'] = date('H:i:s',$vo['rtime']);
            if ($vo['type'] == 'text') {
                $vo['message'] = myTextareaShow($vo['message']);
                $vo['reply'] = myTextareaShow($vo['reply']);
            }elseif($vo['type'] == 'htsc'){
                $vo['message'] = json_decode($vo['message'],true);
            }elseif ($vo['type'] == 'aidraw') {
                $vo['message'] = json_decode($vo['message'],true);
                $vo['reply'] = json_decode($vo['reply'],true);
            }
            
            $msg[$ctime][] = $vo;
        }

        
        $session = Db::name('session')->where('session_sn',$session_sn)->find();
        $session['ctime'] = date('H:i:s',$session['ctime']);
        // $assistant_id = Db::name('session')->where('session_sn',$session_sn)->value('assistant_id');
        $assistant_id = $session['assistant_id'];
        $assistant = Db::name('assistant')->where('id',$assistant_id)->find();

        $wait_msgs = Db::name('htsc')->where([
            ['user_id','=',$ulogin['id']],
            ['status','=',0]
        ])->column('msg_id');
        
        return json(['code'=>2000,'list'=>$msg,'assistant'=>$assistant,'wait_msgs'=>$wait_msgs,'session'=>$session]);
    }

    public function getRpley($id){
        $data = Db::name('msg')->where('id',$id)->find();
        if (empty($data) || empty($data['reply'])) {
            return json(['code'=>5000]);
        }
        if ($data['type'] == 'aidraw') {
            $data['reply'] = json_decode($data['reply'],true);
        }
        return json(['code'=>2000,'data'=>[
            'reply'=>$data['reply'],
            'rtime'=>date('H:i:s',$data['rtime']),
            'type'=>$data['type']
        ]]);
    }

    // 获取指令优化
    public function getPrompt($task_id){
        $data = Db::name('prompt')->where('task_id',$task_id)->find();

        if (empty($data)) {
            return json(['code'=>5000]);
        }
        if ($data['status'] == 0) {
            $api = new baiduApi();
            $result = $api->singleOptimizeInfo($data['task_id']);
            if ($result['status'] == 1) {
                if ($result['data']['processStatus'] == 2) {
                    Db::name('prompt')->where('task_id',$data['task_id'])->update([
                        'status'=>1,
                        'content'=>json_encode($result['data'],JSON_UNESCAPED_UNICODE)
                    ]);

                    return json(['code'=>2000,'data'=>[
                        'content'=>$result['data']['content'],
                        'optimizeContent'=>$result['data']['optimizeContent'],
                    ]]);
                }elseif ($result['data']['processStatus'] == 3){
                    Db::name('prompt')->where('task_id',$data['task_id'])->update([
                        'status'=>-1,
                        'content'=>json_encode($result['data'],JSON_UNESCAPED_UNICODE)
                    ]);
                    return json(['code'=>5001]);
                }
            }

            return json(['code'=>5000]);
        }
        $content = json_decode($data['content'],true);
        return json(['code'=>2000,'data'=>[
            'content'=>$content['content'],
            'optimizeContent'=>$content['optimizeContent'],
        ]]);
    }

    
    public function save(){
        $ulogin = $this->login_user;
        $fields = [
            'must'=>['session_sn','message'],
            'nomust'=>['reply']
        ];
        $save_data = paramFilter(request()->param(),$fields);
        if (!empty($save_data['error_msg'])) {
            return json(['code'=>5000,'msg'=>$save_data['error_msg']]);
        }

        $save_data['user_id'] = $ulogin['id'];
        $assistant_id = Db::name('session')->where('session_sn',$save_data['session_sn'])->value('assistant_id');
        $save_data['assistant_id'] = $assistant_id;
        $save_data['ctime'] = time();
        $save_data['rtime'] = time() + 1;
        $save_data['duration'] = 1;
        $msg_id = Db::name('msg')->insertGetId($save_data);
        
        $result = [
            'code'=>2000,
            'id'=>$msg_id
        ];
        return json($result);
    } 

    // public function save(){
    //     $assistant_id = input('assistant_id');
    //     $ulogin = $this->login_user;

    //     $save_data = [
    //         'user_id'=>$ulogin['id'],
    //         'assistant_id'=>$assistant_id,
    //         'session_sn'=>uuidCreate(),
    //         'ctime'=>time()
    //     ];

    //     MsgModel::insertGetId($save_data);

    //     $assistant = Db::name('assistant')->where('id',$assistant_id)->find();
    //     $msg_data = [
    //         'user_id'=>$ulogin['id'],
    //         'session_sn'=>$save_data['session_sn'],
    //         'message'=>$assistant['description'],
    //         'ctime'=>time(),
    //     ];
    //     Db::name('msg')->insert($msg_data);

        
    //     $result = [
    //         'code'=>2000,
    //         'session_sn'=>$save_data['session_sn'],
    //         'assistant'=>$assistant,
    //         'msg'=>[
    //             'message'=>$msg_data['message'],
    //             'ctime'=>date('y-m-d H:i')
    //         ]
    //     ];
    //     return json($result);
    // }

    public function getMessages($session_sn,$message,$type='baidu'){
        $map = [
            ['session_sn','=',$session_sn]
        ];
        $msgs = Db::name('msg')->field('message,reply')->where($map)->order('id','desc')->limit(3)->select();
        $messages = [];

        if ($type == 'baidu') {
            for($i = 0;$i < count($msgs);$i++){
                if (empty($msgs[$i]['message']) || empty($msgs[$i]['reply'])) {
                    continue;
                }
                $messages[] = [
                    'role'=>'user',
                    'content'=>$msgs[$i]['message']
                ];
                $messages[] = [
                    'role'=>'assistant',
                    'content'=>$msgs[$i]['reply']
                ];
            }
            $messages[] = [
                'role'=>'user',
                'content'=>$message
            ];
            if (count($messages) > 1 && count($messages) % 2 == 0) {
                array_shift($messages);
            }
        }elseif ($type == 'tongyi') {
            for($i = count($msgs) - 1;$i >= 0;$i--){
                if (empty($msgs[$i]['message']) || empty($msgs[$i]['reply'])) {
                    continue;
                }
                $messages[] = [
                    'user'=>$msgs[$i]['message'],
                    'bot'=>$msgs[$i]['reply']
                ];
            }
        }

        return $messages;
    }

    public function getToken($message,$session_sn){
        $ulogin = $this->login_user;
        $message = trim($message);
        if (empty($message)) {
            return json(['code'=>5000]);
        }
        $check_msg = preg_replace("/[^\x{4e00}-\x{9fa5}a-zA-Z0-9]/u", '', $message);
        $check_msg = strtolower($check_msg);
        if (empty($check_msg)) {
            return json(['code'=>5000]);
        }

        $assistant_id = Db::name('session')->where('session_sn',$session_sn)->value('assistant_id');
        $assistant = Db::name('assistant')->where('id',$assistant_id)->find();

        $api_url = $assistant['api_url'];
        $api_param = json_decode($assistant['api_param'],true);

        $uuid = uuidCreate();
        if ($assistant['type'] == 'baidu') {
            $api = new baiduApi();
            $token = $api->token($api_param);
            if (empty($token['access_token'])) {
                return json(['code'=>5000,'msg'=>'token获取失败']);
            }
            $messages = $this->getMessages($session_sn,$message);
            return json(['code'=>2000,'data'=>[
                'api_url'=>$api_url,
                'access_token'=>$token['access_token'],
                'messages'=>$messages,
                'uuid'=>$uuid
            ]]);
        }elseif($assistant['type'] == 'tongyi'){
            $params = [
                'uuid'=>$uuid,
                'message'=>$message,
                'session_sn'=>$session_sn
            ];

            return json(['code'=>2000,'data'=>[
                'api_url'=>$api_url,
                'params'=>$params,
                'uuid'=>$uuid
            ]]);
        }
    }

    

    public function singleOptimize($message=''){
        if ( empty(trim($message)) ) {
            return json(['code'=>5000,'msg'=>'请输入需要优化的指令']);
        }
        $ulogin = $this->login_user;
        $api = new baiduApi();
        // $message = '增程式混动车型和插电式混合车型购买建议';
        $result = $api->singleOptimize($message);
        if ($result['status'] == 1) {
            $task_id = $result['data']['id'];
            Db::name('prompt')->insert([
                'user_id'=>$ulogin['id'],
                'task_id'=>$task_id,
            ]);
            return json(['code'=>2000,'msg'=>'success','data'=>$task_id]);
        }else{
            return json(['code'=>5000,'msg'=>$result['msg']]);
        }
    }


    public function chatapi($message,$session_sn){
        set_time_limit ( 0 );
        ini_set('memory_limit','-1');
        ini_set('max_execution_time',0);

        $ulogin = $this->login_user;

        $curtime = time();
        $message = trim($message);
        if (empty($message)) {
            return json(['code'=>5000]);
        }
        $check_msg = preg_replace("/[^\x{4e00}-\x{9fa5}a-zA-Z0-9]/u", '', $message);
        $check_msg = strtolower($check_msg);
        if (empty($check_msg)) {
            return json(['code'=>5000]);
        }
        

        $assistant_id = Db::name('session')->where('session_sn',$session_sn)->value('assistant_id');
        $assistant = Db::name('assistant')->where('id',$assistant_id)->find();

        $api_url = $assistant['api_url'];
        $api_param = json_decode($assistant['api_param'],true);

        $save_data = [
            'user_id'=>$ulogin['id'],
            'session_sn'=>$session_sn,
            'assistant_id'=>$assistant_id,
            'message'=>$message,
            'ctime'=>$curtime
        ];

        // if ($assistant['type'] == 'justchat') {
        //     $api_url = 'http://brain.digitextend.com/api/ai/get_answer';
        //     $data = [
        //         'app_key'=>'1iizu98ocoy79fpa',
        //         'request_id'=>uuidCreate(),
        //         'timestamp'=>time(),
        //     ];
        //     $data['sign'] = http_build_query($data).'&79575b9988e514121233570d014c776512f4028a';
        //     $data['sign'] = strtoupper(md5($data['sign']));
        //     $data['param'] = [
        //         'session_id'=>$session_id,
        //         'prompt'=>$message,
        //         'voice'=>false
        //     ];

        //     $result = httpRequest($api_url,json_encode($data,JSON_UNESCAPED_UNICODE),'POST',[
        //         'Content-Type:application/json',
        //     ]);
        //     $result = json_decode($result,true);
            
        //     if ($result['code'] == '0') {
        //         $is_success = 1;
        //         $is_shoufei = 1;
        //         $reply = $result['data']['answer'];
        //     }else{
        //         $is_success = 0;
        //         $reply = '这个问题太高深了，容我学习深造后再告诉你';
        //     }
        // }else

        if ($assistant['type'] == 'baidu') {
            $api = new baiduApi();
            $token = $api->token($api_param);
            if (empty($token['access_token'])) {
                return json(['code'=>5000,'msg'=>'token获取失败']);
            }
            $messages = $this->getMessages($session_sn,$message);
            $result = $api->chat($api_url,$token['access_token'],$messages,$assistant['system']);
            
        }elseif ($assistant['type'] == '360') {
            $api = new api360();
            $api_param['session_id'] = $session_sn;
            $result = $api->chat($api_url,$message,$api_param);
        }elseif ($assistant['type'] == 'tongyi') {
            $api = new TongyiApi();
            $history = $this->getMessages($session_sn,$message,'tongyi');
            $messages = [
                'prompt'=>$message
            ];
            if (!empty($history)) {
                $messages['history'] = $history;
            }
            $result = $api->farui($api_url,$messages,$api_param);
        }

        if ($result['status'] == 1) {
            $is_success = 1;
            $is_shoufei = 1;
            $reply = $result['answer'];
            if( strpos($message, '找律师') !== false || strpos($message, '写一份起诉状') !== false || strpos($message, '需要法律援助') !== false ) { 
                $reply .= '<br /><br />可添加微信详细咨询，微信号：delli1120';
            } 
        }elseif ($result['status'] == 2) {
            $is_success = 1;
            $reply = $result['answer'];
            if( strpos($message, '找律师') !== false || strpos($message, '写一份起诉状') !== false || strpos($message, '需要法律援助') !== false ) { 
                $reply .= '<br /><br />可添加微信详细咨询，微信号：delli1120';
            } 
        }else{
            $is_success = 0;
            $reply = '这个问题太高深了，容我学习深造后再告诉你';
        }

        $save_data['reply'] = $reply;
        $save_data['rtime'] = time();
        $save_data['duration'] = time() - $curtime;
        $msg_id = Db::name('msg')->insertGetId($save_data);

        if ($is_success == 1) {
            return json(['code'=>2000,'data'=>myTextareaShow($reply),'id'=>$msg_id]);
        }else{
            return json(['code'=>5000,'data'=>myTextareaShow($reply),'id'=>$msg_id]);
        }
        


        // $save_data = [
        //     'session_id'=>$session_id,
        //     'user_id'=>$user_id,
        //     'msg_time'=>$msg_time,
        //     'reply'=>$reply,
        //     'reply_time'=>date('Y-m-d H:i:s'),
        //     'message'=>$message,
        //     'is_shoufei'=>$is_shoufei,
        //     'type'=>$type,
        //     'role_id'=>$role_id
        // ];
        // // 记录消息回复
        // Db::name('msg')->insert($save_data);
        // if ($is_success == 1) {
        //     // 扣除用户次数
        //     Db::name('user')->where('id',$user_id)->dec('msg_num')->update();
        //     return json(['code'=>2000,'data'=>['type'=>$type,'msg'=>$save_data['reply']]]);
        // }else{
        //     return json(['code'=>5000]);
        // }
        

        
    }

    public function faruiSse($session_sn,$message,$uuid){
        $assistant_id = Db::name('session')->where('session_sn',$session_sn)->value('assistant_id');
        $assistant = Db::name('assistant')->where('id',$assistant_id)->find();

        $api_url = $assistant['api_url'];
        $api_param = json_decode($assistant['api_param'],true);
        $api_param['uuid'] = $uuid;

        $api = new TongyiApi();
        $history = $this->getMessages($session_sn,$message,'tongyi');
        $messages = [
            'prompt'=>$message
        ];
        if (!empty($history)) {
            $messages['history'] = $history;
        }
        $result = $api->faruiSse($api_url,$messages,$api_param);
        if ($result['status'] == 1) {
            // 如果已结束，则保存记录
            if ($result['is_finish'] == 1) {
                $ulogin = $this->login_user;
                $save_data = [
                    'user_id'=>$ulogin['id'],
                    'session_sn'=>$session_sn,
                    'assistant_id'=>$assistant_id,
                    'message'=>$message,
                    'reply'=>$result['answer'],
                    'ctime'=>time(),
                    'rtime'=>time()+1,
                    'duration'=>1,
                ];
                Db::name('msg')->insert($save_data);
            }

            return json(['code'=>2000,'data'=>[
                'reply'=>$result['answer'],
                'is_finish'=>$result['is_finish']
            ]]);
        }else{
            return json(['code'=>2000,'data'=>[
                'reply'=>$result['answer'],
                'is_finish'=>1
            ]]);
        }
    }

    public function htsc(){
        $ulogin = $this->login_user;
        $fields = [
            'must'=>['type','session_sn'],
        ];
        $params = paramFilter(request()->param(),$fields);
        if (!empty($params['error_msg'])) {
            return json(['code'=>5000,'msg'=>$params['error_msg']]);
        }

        // //调用配置文件中的参数
        $bos_config = config('config.baidu_bos');
        // //新建BosClient
        $client = new BosClient($bos_config);
        $bucketName = 'falvai';
        
        $file = $this->request->file('file');
        $ext = explode(".", $file->getInfo()['name']);//拆分获取图片名
        $ext = strtolower($ext[count($ext) - 1]);//取图片的后缀名
        $types = ["pdf", "doc", 'docx'];
        if (!in_array($ext, $types)) {
            return json(['code'=>5000,'msg'=>'仅支持支持PDF/doc/docx格式文件']);
        }
        // 将文件上传到本地
        $info = $file->move('uploads');
        $objectName = uuidCreate().'.'.$ext;
        $name_path =str_replace('\\',"/",$info->getSaveName());//文件存储的路径
        $result = $client->putObjectFromFile($bucketName, $objectName,'uploads/'.$name_path);

        $url = "uploads/".$info->getSaveName();//文件本地目录
        unset($info);//如果不释放这个变量下面的unlink()函数会报错。
        if (file_exists($url)) {
             unlink($url);//删除本地文件
        }
        $file_url = 'https://falvai.bj.bcebos.com/'.$objectName;

        $assistant_id = Db::name('session')->where('session_sn',$params['session_sn'])->value('assistant_id');
        $assistant = Db::name('assistant')->where('id',$assistant_id)->find();

        $message = [
            'name'=>$file->getInfo()['name'],
            'ext'=>$ext,
            'type'=>$params['type'],
            'url'=>$objectName
        ];
        $save_data = [
            'user_id'=>$ulogin['id'],
            'session_sn'=>$params['session_sn'],
            'assistant_id'=>$assistant_id,
            'message'=>json_encode($message,JSON_UNESCAPED_UNICODE),
            'ctime'=>time(),
            'type'=>'htsc'
        ];

        $result = (new baiduApi())->htsc($file_url,$params['type']);
        if ($result['status'] == 1) {
            $msg_id = Db::name('msg')->insertGetId($save_data);
            Db::name('htsc')->insert([
                'msg_id'=>$msg_id,
                'user_id'=>$save_data['user_id'],
                'task_id'=>$result['task_id']
            ]);
            return json(['code'=>2000,'data'=>[
                'message'=>$message,
                'ctime'=>date('Y-m-d H:i:s',$save_data['ctime']),
                'reply'=>'文档已上传成功，正在加急分析中，请稍后',
                'rtime'=>date('Y-m-d H:i:s'),
            ],'msg_id'=>$msg_id]);
        }else{
            $save_data['reply'] = $result['msg'];
            $save_data['rtime'] = time();
            $save_data['duration'] = time() - $save_data['ctime'];
            Db::name('msg')->insert($save_data);
            return json(['code'=>2001,'data'=>[
                'message'=>$message,
                'ctime'=>date('Y-m-d H:i:s',$save_data['ctime']),
                'reply'=>$save_data['reply'],
                'rtime'=>date('Y-m-d H:i:s',$save_data['rtime']),
            ]]);
        }
    }

    public function aiDraw(){
        $ulogin = $this->login_user;
        $fields = [
            'must'=>['prompt','chicun','session_sn'],
            'nomust'=>['num']
        ];
        $params = paramFilter(request()->param(),$fields);
        if (!empty($params['error_msg'])) {
            return json(['code'=>5000,'msg'=>$params['error_msg']]);
        }
        if (empty($params['num'])) {
            $params['num'] = 1;
        }
        if ($params['num'] > 8 || $params['num'] < 1) {
            return json(['code'=>5000,'msg'=>'图片数量请设置在1-8张']);
        }
        $chicun = explode('x',$params['chicun']);

        

        // //调用配置文件中的参数
        // $bos_config = config('config.baidu_bos');
        // // //新建BosClient
        // $client = new BosClient($bos_config);
        // $bucketName = 'falvai';
        
        // $file = $this->request->file('file');
        // $ext = explode(".", $file->getInfo()['name']);//拆分获取图片名
        // $ext = strtolower($ext[count($ext) - 1]);//取图片的后缀名
        // $types = ["pdf", "doc", 'docx'];
        // if (!in_array($ext, $types)) {
        //     return json(['code'=>5000,'msg'=>'仅支持支持PDF/doc/docx格式文件']);
        // }
        // // 将文件上传到本地
        // $info = $file->move('uploads');
        // $objectName = uuidCreate().'.'.$ext;
        // $name_path =str_replace('\\',"/",$info->getSaveName());//文件存储的路径
        // $result = $client->putObjectFromFile($bucketName, $objectName,'uploads/'.$name_path);

        // $url = "uploads/".$info->getSaveName();//文件本地目录
        // unset($info);//如果不释放这个变量下面的unlink()函数会报错。
        // if (file_exists($url)) {
        //      unlink($url);//删除本地文件
        // }
        // $file_url = 'https://falvai.bj.bcebos.com/'.$objectName;

        $assistant_id = Db::name('session')->where('session_sn',$params['session_sn'])->value('assistant_id');
        $assistant = Db::name('assistant')->where('id',$assistant_id)->find();

        $message = [
            // 'name'=>$file->getInfo()['name'],
            // 'ext'=>$ext,
            // 'type'=>$params['type'],
            // 'url'=>$objectName
            'prompt'=>$params['prompt'],
            'chicun'=>$params['chicun'],
            'num'=>$params['num']
        ];
        $save_data = [
            'user_id'=>$ulogin['id'],
            'session_sn'=>$params['session_sn'],
            'assistant_id'=>$assistant_id,
            'message'=>json_encode($message,JSON_UNESCAPED_UNICODE),
            'ctime'=>time(),
            'type'=>'aidraw'
        ];

        $api = new baiduApi();
        $token = $api->token([
            'client_id'=>'nuCDgwPHzU3JSCZ9BaahYT44',
            'client_secret'=>'LlyWXJJJD3ew7vFC27kxBWwJspR6nSn3'
        ]);
        if (empty($token['access_token'])) {
            return json(['code'=>5000,'msg'=>'token获取失败']);
        }
        $result = $api->txt2imgv2($token['access_token'],[
            'prompt'=>$params['prompt'],
            'width'=>intval($chicun[0]),
            'height'=>intval($chicun[1]),
            'image_num'=>intval($params['num'])
        ]);
        if ($result['status'] == 1) {
            $msg_id = Db::name('msg')->insertGetId($save_data);
            Db::name('aidraw')->insert([
                'msg_id'=>$msg_id,
                'user_id'=>$save_data['user_id'],
                'task_id'=>$result['task_id']
            ]);
            return json(['code'=>2000,'data'=>[
                'message'=>$message,
                'ctime'=>date('H:i:s',$save_data['ctime']),
                'reply'=>'请求发送成功，正在加急生成中，请稍后',
                'rtime'=>date('H:i:s'),
            ],'msg_id'=>$msg_id]);
        }else{
            $save_data['reply'] = $result['msg'];
            $save_data['rtime'] = time();
            $save_data['duration'] = time() - $save_data['ctime'];
            Db::name('msg')->insert($save_data);
            return json(['code'=>2001,'data'=>[
                'message'=>$message,
                'ctime'=>date('H:i:s',$save_data['ctime']),
                'reply'=>$save_data['reply'],
                'rtime'=>date('H:i:s',$save_data['rtime']),
            ]]);
        }
    }

    public function chatapi2(){
        set_time_limit ( 0 );
        ini_set('memory_limit','10240M');

        $list = Db::name('problem')->where(Db::raw('category is null'))->select();
        $api = new baiduApi();
        foreach ($list as $k => $vo) {
            // $message = "基于弹性计算,数据库,存储,网络与CDN,安全,容器,中间件,大数据,人工智能,物联网，这10个分类，根据题目'''".($vo['title'])."'''中的内容，判断内容属于哪个分类，要求输出JSON格式：{\"category\":\"分类名称\"}";
            $message = "题目：".($vo['title'])."，这题目属于[弹性计算|数据库|存储|网络与CDN|安全|容器|中间件|大数据|物联网]当中哪个分类，要求输出JSON格式：{\"category\":\"分类名称\"}";
            $result = (new baiduApi())->chat2($message);
            
            if ($result['status'] == 1) {
                $content = $result['answer'];
                // $content = str_replace(['```json','```'], '', $content);
                preg_match('/\{([^}]+)\}/', $content, $output);
                $content = json_decode($output[0],true);
                if (!empty($content['category']) && in_array($content['category'],['弹性计算','数据库','存储','网络与CDN','安全','容器','中间件','大数据','人工智能','物联网'])) {
                    Db::name('problem')->where('id',$vo['id'])->update([
                        'category'=>$content['category']
                    ]);
                }
            }
        }
        echo 'success';die;
        dump($list);die;

        

        
        
    }


   
}
